import { useContext, useEffect, useState } from 'react';
import NamePostIdH5Page from '@/app/[locale]/mobile/posts/[id]/name';
import ContentPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/content';
import ButtonAreaPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/buttonArea';
import StatementPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/statement';
import CommentPostIdH5Page from '@/app/[locale]/mobile/posts/[id]/comment';
import LoadMoreBtn from '@/app/[locale]/mobile/posts/[id]/loadMoreBtn';
import H5Box from '@/app/[locale]/common/other/h5';
import { PostIdPageContext } from '@/contexts/post-id';
import useToast from '@/hooks/useToast';
import type { IPostClientDetails, IPostComment } from '@/interfaces';
import { useInfiniteQuery } from '@tanstack/react-query';
import { clientQueryPostDetails } from '@/services/api';
import { toRelativeTime } from '@/lib/tool';

export default function PostIdH5Page() {
  const {
    source: { postDetails },
    translatedFields,
  } = useContext(PostIdPageContext)!;
  const { show } = useToast();
  const [pages, setPages] = useState<IPostComment[]>(postDetails.data.content);
  const queryKey = [
    '/forum',
    '/posts',
    '/client',
    postDetails.basic.id,
    '/details',
    'infinite',
  ];

  const clientQueryPostDetailsQuery = useInfiniteQuery(
    queryKey,
    async (context) => {
      return (await clientQueryPostDetails({
        id: context.queryKey[3],
        query: context.pageParam,
      })) as IPostClientDetails;
    },
    {
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (!firstPage.data!.pageable.previous) {
          return;
        }
        return {
          page: Math.max(firstPage.data!.pageable.page - 1, 0),
        };
      },
      getNextPageParam: (lastPage) => {
        if (!lastPage.data!.pageable.next) {
          return;
        }
        return {
          page: Math.min(
            lastPage.data!.pageable.page + 1,
            lastPage.data!.pageable.pages,
          ),
        };
      },
      initialData: () => {
        return {
          pages: [postDetails],
          pageParams: [{ page: 0 }],
        };
      },
    },
  );

  useEffect(() => {
    function handleContent(item: IPostComment) {
      item.comment._createdOnText = toRelativeTime(item.comment.createdOn);
      item.content.forEach((value) => {
        value.reply._createdOnText = toRelativeTime(value.reply.createdOn);
        value.content.forEach((value1) => {
          value1.reply._createdOnText = toRelativeTime(value1.reply.createdOn);
          value1.content.forEach((value2) => {
            value2.reply._createdOnText = toRelativeTime(
              value2.reply.createdOn,
            );
          });
        });
      });
      return item;
    }

    if (clientQueryPostDetailsQuery.data) {
      setPages(
        clientQueryPostDetailsQuery.data.pages
          .flatMap((item) => {
            item.basic._contentUpdatedOnText = toRelativeTime(
              item.basic.contentUpdatedOn,
            );
            return item.data.content;
          })
          .map(handleContent),
      );
    }
  }, [clientQueryPostDetailsQuery.data]);

  async function onClickLoadMore() {
    try {
      await clientQueryPostDetailsQuery.fetchNextPage();
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <H5Box classs="col px-2 py-4 vstack gap-2">
      <div className="vstack gap-2">
        <div className="card rounded-5 border-0">
          <div className="card-body vstack gap-4">
            <NamePostIdH5Page />
            <ContentPostIdH5Page />
            <StatementPostIdH5Page />
            <ButtonAreaPostIdH5Page />
          </div>
        </div>

        {postDetails.data.content.length > 0 && (
          <div className="card rounded-5 border-0">
            <div className="card-body vstack gap-4">
              <div>{translatedFields.allReply}</div>
              <CommentPostIdH5Page pages={pages} />
              <LoadMoreBtn
                isLoading={clientQueryPostDetailsQuery.isLoading}
                onClickLoadMore={onClickLoadMore}
              />
            </div>
          </div>
        )}
      </div>
    </H5Box>
  );
}
